<?php
/**
 * 公开接口API
 * 学生社团等接口
 * 不需要验证用户身份token
 * @author David
 * ok
 */
namespace Api\Controller;

use Common\Controller\ApiController;
use Think\Page;

class CommunityController extends ApiController{

    //我的社团（状态为：1-已通过、0-申请中、-1-被拒绝）
    public function getMyClub()
    {
        $uid=$this->member_info['member_id'] ? $this->member_info['member_id'] : 0;
        $table='club';
        $cond=array('uid'=>$uid);
        $cond['status']=$_REQUEST['status'];
        $page=$this->comMod->initPage($table,$cond,$this->pageNum);
        $totalPages = ceil($page->totalRows / $page->listRows); 
        $extend_data = $this->mobile_page($totalPages);
        $list=$this->comMod->getList($table,$cond,'*','status desc,id desc',$page->firstRow,$page->listRows);
        $club_list=array();
        foreach ($list as $key => $value) {
            $value['status_desc']=$this->transform_club_status($value['status']);
            $club_list[]=$this->communityMod->clubHandle($value);
        }

        $this->myApiPrint(200,$club_list,$extend_data);
    }

    //删除被拒绝的请求
    // public function ClubApplyDelete()
    // {
    //     $uid=$this->member_info['member_id'] ? $this->member_info['member_id'] : 0;
    //     $table='club';
    //     $cond=array('uid'=>$uid);
    //     $cond['status']=-1;
    //     $result=$this->comMod->delData($table,$cond);

    //     if($result){
    //         $this->myApiPrint(200);
    //     }else{
    //         $this->myApiPrint(-3);
    //     }
    // }

    //修改协会历史，现状，未来
    public function editClubInfo()
    {
        $uid=$this->member_info['member_id'] ? $this->member_info['member_id'] : 0;
        $condition['id']=$_REQUEST['cid'];
        $club=$this->comMod->detail('club',$condition,'uid');

        //创建者才能修改
        if(empty($club['uid']) || (isset($club['uid']) && $club['uid']!=$uid)){
            $this->myApiPrint(-3,'',array('msg'=>'该社团不存在或没有权限操作'));
        }

        if(!empty($_REQUEST['history'])){
           $data['history']=$_REQUEST['history']; 
        }

        if(!empty($_REQUEST['present'])){
           $data['present']=$_REQUEST['present']; //现状
        }

        if(!empty($_REQUEST['future'])){
           $data['future']=$_REQUEST['future'];
        }

        try {
            $this->comMod->saveData('club',$condition,$data);  //逻辑删除
            $this->myApiPrint(200);
        } catch (Exception $e) {
            $this->myApiPrint(-3);
        }
    }

    //申请创建社团
    public function createClub()
    {
        $uid=$this->member_info ? $this->member_info['member_id'] : 0;
        $city_id=$_REQUEST['city_id'] ? $_REQUEST['city_id'] : 0;
        $member_info=$this->comMod->getMemberInfoByID($uid,'member_name,member_id,school');
        $school_info=unserialize($member_info['school']);
        extract($school_info);
        unset($school_info);
        if($school_id==''){
            $this->myApiPrint(4010);
        }
        if(!$city_id){
            $this->myApiPrint(-3,'',array('msg'=>'未定位到城市信息'));
        }
        $info['city_id'] = $city_id;
        $info['uid'] = $uid;
        $info['name'] = $_REQUEST['name'];
        $info['type'] = $_REQUEST['type'];
        $info['level'] = $_REQUEST['level'];//传字符串
        $info['desc'] = $_REQUEST['desc'];
        $info['time'] = NOW_TIME;
        $info['school_id']=$school_id ? $school_id : 0;//0-社会组织，1-校级组织
        $info['history'] = "";
        $info['present'] = "";
        $info['future'] = "";
        $info['status']=0; //0-等待审核，1-通过审核，-1-审核不通过
        //图片上传
        if(!empty($_FILES['file']['size']))
        {
            $arc_img = 'club_cover_'.$info['uid'];
            $param = array('savePath'=>'club/club_cover/','subName'=>'','files'=>$_FILES['file'],'saveName'=>$arc_img,'saveExt'=>'');
            $up_return = upload_one($param);
            if($up_return == 'error'){
                $this->myApiPrint(4005);
            }else{
                $info['logo'] = $up_return;
            }
        }

        $member_info=$this->comMod->detail('member',array('member_id'=>$uid),'student_photo,identification_photo');

        if(!empty($member_info['self_photo'])){
            $info['identification_photo'] = $member_info['identification_photo'];
        }else{
            //上传证件照
            if(!empty($_FILES['identification_photo']['size']))
            {
                $arc_img = 'identification_photo'.$info['uid'];
                $param = array('savePath'=>'member/identification_photo/','subName'=>'','files'=>$_FILES['identification_photo'],'saveName'=>$arc_img,'saveExt'=>'');
                $up_return = upload_one($param);
                if($up_return == 'error'){
                    $this->myApiPrint(4005);
                }else{
                    $info['identification_photo'] = $up_return;
                }
            }
        }
        
        if(!empty($member_info['student_photo'])){
            $info['student_photo'] = $member_info['student_photo'];
        }else{
            //上传学生证照
            if(!empty($_FILES['student_photo']['size']))
            {
                $arc_img = 'student_photo'.$info['uid'];
                $param = array('savePath'=>'member/student_photo/','subName'=>'','files'=>$_FILES['student_photo'],'saveName'=>$arc_img,'saveExt'=>'');
                $up_return = upload_one($param);
                if($up_return == 'error'){
                    $this->myApiPrint(4005);
                }else{
                    $info['student_photo'] = $up_return;
                }
            }
        }
         
        //保存数据
        $result =  M("club")->add($info);
        
        if($result){
            
            //更新用户信息
            $memmber_data=array();
            if(!empty($info['student_photo'])){
                $memmber_data['student_photo']=$info['student_photo'];
            }
            if(!empty($info['identification_photo'])){
                $memmber_data['identification_photo']=$info['identification_photo'];
            }
            if(!empty($memmber_data)){
                $this->comMod->saveData('member',array('member_id'=>$uid),$memmber_data); 
            }
            
            $this->myApiPrint(201);
        }else{
            $this->myApiPrint(-3);
        }
    }
	
    //社团创建申请列表
    public function getClubApplyList()
    {
        $table='club';
        $cond=array('uid'=>$this->member_info['member_id']);
        $cond['status']=0;
        $page=$this->comMod->initPage($table,$cond,$this->pageNum);
        $totalPages = ceil($page->totalRows / $page->listRows); 
        $extend_data = $this->mobile_page($totalPages);
        $list=$this->comMod->getList($table,$cond,'*','id desc',$page->firstRow,$page->listRows);
        $club_list=array();
        foreach ($list as $key => $value) {
            $club_list[]=$this->communityMod->clubHandle($value);
        }

        $this->myApiPrint(200,$club_list,$extend_data);

    }

    //学生社团类型列表
    public function getClubTypeList()
    {   

        $table="club_type";
        $cond['show']=1;
        $cond['pid']=$_REQUEST['pid'] ? $_REQUEST['pid'] : 0;
        $list=$this->comMod->getList($table,$cond,'*','sort desc,id asc');
        $this->myApiPrint('',$list);

    }
    
    //根据类型返回不同类型的的学生社团列表、全国社团(ok)
    public function getClubList()
    {
        $city_id=$_REQUEST['city_id'] ? $_REQUEST['city_id'] : 0;
        $condition=array();
        $condition['status']=1;  //审核通过
        $table=C('DB_PREFIX')."club";
        $table_ct=C('DB_PREFIX')."club_type";
        if(intval($_REQUEST['type'])){
            $condition['type']=$_REQUEST['type'];  //社团类型
        }
        //搜索社团名称
        if(intval($_REQUEST['name'])){
            $condition['name']=array('like','%'.$_REQUEST['name'].'%');  //社团类型
        }

        //获取用户学校信息
        $member_info=$this->comMod->getMemberInfoByID($this->member_info['member_id'],'member_name,member_id,school');
        extract(unserialize($member_info['school']));

        if($_REQUEST['level']=='1'){
            //本校社团
            $condition['school_id']=$school_id;
        }else{
            //全国社团
            // $condition['school_id']=0;
            //某个城市的所有社团
            $condition['city_id']=$city_id;
            $condition['school_id']=array('neq',$school_id);
        }

        // $this->myApiPrint(-3,'',array('msg'=>'level id:'.$_REQUEST['level'].'----学校id：'.$school_id.'----'.'城市id：'.$city_id));

        //默认全部社团
        $count = $this->comMod->table($table)->where($condition)->count();
        $page = new Page($count,$this->pageNum);
        $totalPages = ceil($page->totalRows / $page->listRows); //总页数
        $extend_data= $this->mobile_page($totalPages);
        $club_list=array();
        $list=$this->comMod->table($table)->where($condition)->limit($page->firstRow,$page->listRows)->order('count desc,id desc')->select();
        ;
        // echo $this->comMod->getLastSql();
        $label_data=$this->comMod->table($table_ct)->where(array('show'=>1))->limit(0,20)->order('sort desc,id desc')->select();
        ;
        foreach ($label_data as $key => $value) {
            $extend_data['typeData'][]=$value;
        }
        foreach ($list as $key => $value) {
            $club_list[]=$this->communityMod->clubHandle($value);
        }
        $this->myApiPrint('',$club_list,$extend_data);
    }

    //社团主页面(ok)
    public function getClubPage(){
        $list=array();
        $extend_data=array();
        $extend_data['actData']=array();
        $extend_data['myschoolClub']=array();
        $extend_data['allClub']=array();
        $city_id=$_REQUEST['city_id'] ? $_REQUEST['city_id'] : 0;
        // $this->myApiPrint(-3,'',array('msg'=>$city_id));
        $city_club_condition=array();
        if($this->member_info['member_id']){
            $member_info=$this->comMod->getMemberInfoByID($this->member_info['member_id'],'member_name,member_id,school');
            extract(unserialize($member_info['school']));
            $school_id=$school_id ? $school_id : 0;
            if($school_id){
                $myschoolClub=$this->comMod->getList('club',array('status'=>1,'school_id'=>$school_id),'*','count desc,id desc',0,5);
            }

        }
        
        if($city_id){
            $city_club_condition['city_id']=$city_id;
            if($school_id){
                $city_club_condition['school_id']=array('neq',$school_id);
            }
            // $this->myApiPrint(-3,'',array('msg'=>'学校id：'.$school_id.'----'.'城市id：'.$city_id));
            //获取某城市社团
            $allClub=$this->comMod->getList('club',$city_club_condition,'*','count desc,id desc',0,5);
        }

        
        // $allClub=$this->comMod->getList('club',array('status'=>1,'school_id'=>0),'*','count desc,id desc',0,5);

        $typeData=$this->comMod->getList('club_type',array('show'=>1),'*','sort desc,id desc',0,12);

        $actData=M('adv_position')->where(array('ap_code'=>'banner_community_aid'))->select();

        $table='sectiontopic';
        $order='latest_comment_time desc,article_id desc';
        $condition['article_show']=1;
        $condition['city_id']=$city_id;
        $condition['ac_id']=24;
        $condition['cid']=array('neq',0);
        $image_list=$this->comMod->getList($table,$condition,'*',$order,0,7);
        $condition['ac_id']=25;
        $video_list=$this->comMod->getList($table,$condition,'*',$order,0,7);
        $condition['ac_id']=26;
        $document_list=$this->comMod->getList($table,$condition,'*',$order,0,7);

        //社团分类标签
        $extend_data['typeData']=$typeData;
        //幻灯片
        foreach($actData as $key=>$value){
            $extend_data['actData'][] = $this->comMod->advMapping($value);
        }
        //本校社团
        foreach ($myschoolClub as $key => $value) {
            $extend_data['myschoolClub'][]=$this->communityMod->clubHandle($value);
        }
        //本市社团
        foreach ($allClub as $key => $value) {
            $extend_data['allClub'][]=$this->communityMod->clubHandle($value);
        }
        //集锦照片区域
        foreach($image_list as $key=>$value){
            $value2=$this->comMod->bangdanHandle($value);
            if($key<3){
                $imageData[0]['layoutType']='1';
                $imageData[0]['itemData'][]=$value2;
            }else{
                $imageData[1]['layoutType']='2';
                $imageData[1]['itemData'][]=$value2;
            }
            unset($value2);
        }
        //集锦视频区域
        foreach($video_list as $key=>$value){
            $value2=$this->comMod->bangdanHandle($value);
            if($key<3){
                $videoData[0]['layoutType']='1';
                $videoData[0]['itemData'][]=$value2;
            }else{
                $videoData[1]['layoutType']='2';
                $videoData[1]['itemData'][]=$value2;
            }
            unset($value2);
        }
        //集锦文档区域
        foreach($document_list as $key=>$value){
            $value2=$this->comMod->bangdanHandle($value);
            $document_list[$key]=$value2;
            unset($value2);
        }

        $extend_data['imageData']=$imageData ? $imageData : array();
        $extend_data['videoData']=$videoData ? $videoData : array();
        $extend_data['documentData']=$document_list ? $document_list : array();

        $this->myApiPrint('','',$extend_data);
    }

    //活动集锦照片专区、视频、文档专区
    public function getActivityThemeList()
    {   

        $order='latest_comment_time desc,article_id desc';
        $table='sectiontopic';
        $cond=array();
        $type=$_REQUEST['type'];
        $cond['ac_id']=$type;
        $cond['cid']=array('neq',0); //所有社团
        $cond['article_show']=1;
        
        $page=$this->comMod->initPage($table,$cond,$this->pageNum);
        $totalPages = ceil($page->totalRows / $page->listRows);
        $offset=$page->firstRow;
        $limit=$page->listRows; 
        $extend_data = $this->mobile_page($totalPages);
        $list=$this->comMod->getList($table,$cond,'*',$order,$offset,$limit);
        $data_lsit=array();
        foreach($list as $key=>$value){
                $data_lsit[]=$this->comMod->bangdanHandle($value);
            }

        $this->myApiPrint('',$data_lsit,$extend_data);
    }

    //社团详情（ok）
    public function getClubDetail()
    {
        $uid=$this->member_info ? $this->member_info['member_id'] : 0;
        $type=$this->getSwitchType($_REQUEST['type']);
        $table='sectiontopic';
        $order='article_sort desc,article_id desc';
        $cond['cid']=$_REQUEST['cid'];
        $cond['article_show']=1;
        $condition['id']=$_REQUEST['cid'];
        
        $detail=$this->communityMod->getClubDetail($condition);
        //判断是否管理员
        $detail['is_admin']=0;
        if($uid && $uid==$detail['uid']){
            $detail['is_admin']=1; //是管理员
        }
        //判断加入情况
        $club_join=$this->comMod->detail('club_join',array('cid'=>$_REQUEST['cid'],'uid'=>$uid),'status');
        $join_status=$club_join ? $club_join['status'] : 3;
        switch ($join_status) {
            case 0:
                $detail['is_join']='等待审核'; 
                break;
            case -1:
                $detail['is_join']='申请加入'; //申请被拒
                break;
            case 1:
                $detail['is_join']='已加入'; 
                break;
            case 2:
                $detail['is_join']='申请加入'; //用户被踢出
                break;
            default:
                $detail['is_join']='申请加入';  //用户未申请过
                break;
        }
        if($detail['is_admin']){
            $detail['is_join']='审核申请';
        }
        $detail['listData']=array();
        if($type!=''){
            $cond['ac_id']=$type;
            $page=$this->comMod->initPage($table,$cond,$this->pageNum);
            $totalPages = ceil($page->totalRows / $page->listRows); 
            $offset=$page->firstRow;
            $limit=$page->listRows;
            $extend_data = $this->mobile_page($totalPages);
            $order='latest_comment_time desc,article_id desc';
            $cur_page = intval($_REQUEST['curpage']);//当前页数
            if(in_array($type, array(24,25))){
                if($cur_page>1){
                    $offset=$offset-1;
                }else{
                    $limit=9;
                }
            }
            
        }else{
            //最新活动
            $cond['ac_id']=23;
            $offset=0;
            $limit=6;

        }

        $actData = $this->comMod->getList($table,$cond,'*',$order,$offset,$limit);
        //照片、视频
        if(in_array($type, array(24,25))){
            foreach($actData as $key=>$value){
                $value2=$this->comMod->bangdanHandle($value);
                if ($cur_page==1) {
                    if($key<3){
                        $specialData[0]['layoutType']='1';
                        $specialData[0]['itemData'][]=$value2;
                    }else{
                        $specialData[1]['layoutType']='2';
                        $specialData[1]['itemData'][]=$value2;
                    }
                }else{
                    $specialData[0]['layoutType']='2';
                    $specialData[0]['itemData'][]=$value2;

                }
                unset($value2);
            }
            $detail['listData']= $specialData ? $specialData : array();
        }else{
            //活动、文档、介绍
            foreach ($actData as $key => $value) {
                $detail['listData'][]= $this->comMod->bangdanHandle($value);
            }
        }

        //社团成员
        $admin_detail=$this->comMod->detail('member',array('member_id'=>$detail['uid']),'member_id,avatar,member_name');
        $admin_detail['icon']= $admin_detail['avatar'] ? PicPath.$admin_detail['avatar'] : '';
        $admin_detail['uid']= $admin_detail['member_id'] ? $admin_detail['member_id'] : 0;
        $admin_detail['name']= $admin_detail['member_name'] ? $admin_detail['member_name'] : '';
        unset($admin_detail['avatar']);
        unset($admin_detail['member_id']);
        unset($admin_detail['member_name']);
        $members=array($admin_detail);  //第一个成员为管理员
        $uids=$this->comMod->getList('club_join',array('cid'=>$_REQUEST['cid'],'status'=>1),'uid','id desc',0,8);
        foreach ($uids as $key => $value) {
            $club_user=$this->comMod->detail('member',array('member_id'=>$value['uid']),'member_id,avatar,member_name');
            $club_user['icon']= $club_user['avatar'] ? PicPath.$club_user['avatar'] : '';
            $club_user['uid']= $club_user['member_id'] ? $club_user['member_id'] : 0;
            $club_user['name']= $club_user['member_name'] ? $club_user['member_name'] : '';
            unset($club_user['avatar']);
            unset($club_user['member_id']);
            unset($club_user['member_name']);
            $members[]=$club_user;
        }
        
        // print_r($members);exit;
        // $members=$this->communityMod->clubMemberHandle($members);
        $detail['memberData']= $members;

        $this->myApiPrint(200,$detail,$extend_data);
    }


    //活动详情、文档详情(ok)
    public function getActivityDetail()
    {
        $condition['article_id']=$_REQUEST['tid'];
        $condition['article_show']=1;
        $detail=$this->bangdanMod->getBandanTopicDetail($condition);
        $detail['view']=$detail['view']+1;
        if(empty($detail['member_id'])){
            $this->myApiPrint(-3,'',array('msg'=>'该文章不存在或没有权限操作'));
        }
        
        //查询是否喜欢
        $zanstatus=$this->bangdanMod->getTopicSelfZanStatus($_REQUEST['tid'],$this->member_info);
        if($zanstatus){
            $detail['isLike']='1'; //喜欢
        }else{
            $detail['isLike']='0'; //不喜欢
        }

        if($_REQUEST['refresh']){
            $this->myApiPrint(200,$detail,$extend_data);  //在本页面刷新不计入浏览数更新
        }else{
            $detail['view']=$detail['view']+1;
        }
        
        //更新浏览数
        $cond['article_id']=$_REQUEST['tid'];
        $result=$this->comMod->selfUpdateField('sectiontopic','view',$cond,$operate="+",1);//浏览数+1
        $this->myApiPrint('',$detail);
    }

    // //文档详情(ok)
    // public function getArticleDetail()
    // {
    //     // $condition['uid']=$_REQUEST['uid'];
    //     $condition['article_id']=$_REQUEST['tid']; //文档id
    //     $detail=$this->bangdanMod->getBandanTopicDetail($condition);
    //     //查询是否喜欢
    //     $zanstatus=$this->bangdanMod->getTopicSelfZanStatus($_REQUEST['tid'],$this->member_info);
    //     if($zanstatus){
    //         $detail['isLike']='1'; //喜欢
    //     }else{
    //         $detail['isLike']='0'; //不喜欢
    //     }
    //     $this->myApiPrint('',$detail);
    // }

    //申请社团
    public function joinClub()
    {
        //检查是否存在申请
        $uid=$this->member_info ? $this->member_info['member_id'] : 0;
        if(!$uid){
            $this->myApiPrint('-2');
        }
        $join_record=$this->comMod->detail('club_join',array('cid'=>$_REQUEST['cid'],'uid'=>$uid),$fields='*');
        $join_status=$join_record ? $join_record['status'] : 3;
        if($join_status==1 || $join_status==0){
            $this->myApiPrint(4006); //已经是成员或申请中
        }

        //图片上传
        if(!empty($_FILES['pic']['size']))
        {
            $arc_img = 'pic'.$uid;
            $param = array('savePath'=>'club/aid_join/','subName'=>'','files'=>$_FILES['pic'],'saveName'=>$arc_img,'saveExt'=>'');
            $up_return = upload_one($param,0);
            if($up_return == 'error'){
                $this->myApiPrint(4005);
            }else{
                $info['img'] = $up_return;
            }
        }

        //保存数据
        $club_info=$this->communityMod->getClubDetail(array('cid'=>$_REQUEST['cid']), $fields = 'name');
        $info['uid'] = $uid;
        $info['cid'] = $_REQUEST['cid'];
        $info['club_name'] = $club_info['name'];
        $info['add_time'] = NOW_TIME;
        if($join_status==3){
            //不存在申请记录
            $result =  M("club_join")->add($info);
        }else{
            //存在申请记录
            $cond['uid']=$uid;
            $cond['cid']=$_REQUEST['cid'];
            unset($info['uid']);
            unset($info['cid']);
            $info['status']=0; //修改为待审核状态
            $result =  M("club_join")->where($cond)->save($info);
        }
        
        if($result){
            $this->myApiPrint(200);
        }else{
            $this->myApiPrint(-3);
        }
    }

    //单个社团申请列表（社团管理员）
    public function getApplyList()
    {
        $uid=$this->member_info ? $this->member_info['member_id'] : 0;
        $condition=array();
        $table=C('DB_PREFIX')."club_join";
        $condition['status']=0;
        $condition['cid']=$_REQUEST['cid']; 
        $count = $this->comMod->table($table)->where($condition)->count();
        $page = new Page($count,$this->pageNum);
        $totalPages = ceil($page->totalRows / $page->listRows); //总页数
        $extend_data= $this->mobile_page($totalPages);
        $list=$this->comMod->table($table)->where($condition)->limit($page->firstRow,$page->listRows)->order($order)->select();
        ;
        foreach ($list as $key => $value) {
            $list[$key]=$this->communityMod->clubApplyHandle($value);
        }
        $this->myApiPrint('',$list,$extend_data);
    }

    //通过/拒绝申请审核
    public function allowApply()
    {
        $status=$_REQUEST['status']==-1 ? -1 : 1;

        $data=array('status'=>$status);
        $condition['id']=$_REQUEST['id'];
        $result=M("club_join")->where($condition)->save($data);
        if($result){
            $this->myApiPrint(200);
        }else{
            $this->myApiPrint(-3);
        }
    }

    public function getSwitchType($type){

        switch ($type)
        {
            case 'introduce': //社团介绍主页
                $type='';
                break;
            case 'activity': //活动预热
                $type='23';
                break;
            case 'image': //照片
                $type='24';
                break;
            case 'video': //视频
                $type='25';
                break;
            case 'document': //文档
                $type='26';
                break;
        }
        return $type;
    }

}